import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName Demo03_SerializableTest
 * @Description 练习：序列化集合
 * 将存有多个自定义对象的集合序列化操作，保存到 list.txt 文件中
 * 反序列化 list.txt ，并遍历集合，打印对象信息
 * @Author Li
 * @Date 2022/8/12 21:11
 * @ModifyDate 2022/8/12 21:11
 * @Version 1.0
 */
public class Demo03_SerializableTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String filename = "src/part10/ch03_Serializable/list.txt";
        // 创建序列化流并写入对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
        List<Student> list = new ArrayList<>();
        list.add(new Student("张三", 18, 101));
        list.add(new Student("李四", 19, 102));
        list.add(new Student("王二", 18, 103));
        oos.writeObject(list);
        // 释放资源
        oos.close();
        // 创建反序列化流并读取文件
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
        ArrayList<Student> students = (ArrayList<Student>) ois.readObject();
        // 关闭资源
        ois.close();
        // 遍历读取的反序列化文件
        for (Student student : students) {
            System.out.println(student);
        }
    }
}
